package Concurrency2.Inteview01_ThreadPool.version04;

import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 作用: 线程池的工作线程
 * version04-增加保活时间, 优化线程
 */
public class WorkerThread extends Thread {
    //属性: 任务队列
    private BlockingQueue<Runnable> taskQueue;
    // 属性: 当前线程保活时间
    private long keepAliveTime;
    // 属性: 线程池工作线程容器
    private List<WorkerThread> workerThreads;
    private static AtomicInteger workerId = new AtomicInteger();

    public WorkerThread(BlockingQueue<Runnable> taskQueue, long keepAliveTime, List<WorkerThread> workerThreads) {
        this.taskQueue = taskQueue;
        this.keepAliveTime = keepAliveTime;
        this.workerThreads = workerThreads;
        // 创建日志
        System.out.println("Worker Thread ID: " + workerId.incrementAndGet() + " creation completed.");
    }

    /**
     * 作用: 获取任务队列taskQueue中的任务, 并执行.
     */
    @Override
    public void run() {
        // 初始化激活时间
        long lastActiveTime = System.currentTimeMillis();

        while (!Thread.currentThread().isInterrupted()) {
            try {
                //Runnable task = taskQueue.take();
                //task.run(); // 直接调用Thread的run()方法, 而不是调用start()方法启动一个线程.
                // 1, 在阻塞队列中获取任务
                Runnable task = taskQueue.poll(keepAliveTime, TimeUnit.MILLISECONDS);
                if (task != null) {
                    // 2, 获取到任务, 执行, 并更新激活时间
                    task.run();
                    lastActiveTime = System.currentTimeMillis();
                } else if ((System.currentTimeMillis() - lastActiveTime) >= keepAliveTime) {
                    // 2, 没有获取到任务, 并且超出保活时间, 则结束循环, 当前线程将结束
                    workerThreads.remove(this);
                    System.out.println(">>> ThreadID:" + Thread.currentThread().getId() + "超时 removed.<<<");
                    break;
                }
            } catch (InterruptedException e) {
                workerThreads.remove(this);
                e.printStackTrace();
                break; //被中断退出循环
            }
        }
    }
}
